package com.vimi8.ebb.api.train;

import com.vimi8.ebb.configuration.HttpResponseEntity;
import com.vimi8.ebb.dto.TrainInfoDataRepport;
import com.vimi8.ebb.dto.TrainInfoTotalDto;
import com.vimi8.ebb.dto.TrainMemberDto;
import com.vimi8.ebb.model.*;
import com.vimi8.ebb.model.Error;
import com.vimi8.ebb.service.GeoCodingsService;
import com.vimi8.ebb.service.TrainInfoService;
import com.vimi8.ebb.service.TrainMemberService;
import com.vimi8.ebb.util.JxlExcelUtil;
import com.vimi8.ebb.util.PagesUtil;
import com.vimi8.ebb.util.SubStringUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * Created by think on 2016/12/5.
 */
@RestController
@RequestMapping("/front/train")
public class FrontTrainController
{
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TrainInfoService trainInfoService;
    @Autowired
    private GeoCodingsService geoCodingsService;
    @Autowired
    private TrainMemberService trainMemberService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @ApiOperation(value = "查询培训信息",notes = "查询培训信息",response = String.class,tags = {"培训信息(前端)"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/",method = RequestMethod.GET)
    public HttpResponseEntity<Paginator<List<TrainInfo>>> getFrontTrainInfo(@ApiParam(value = "培训标题",required = false) @RequestParam(value = "trainTitle",required = false) String  trainTitle,
                                                                       @ApiParam(value = "是否是按培训时间降序",required = false) @RequestParam(value="isTrainDateDesc",required = false)String isTrainDateDesc,
                                                                       @ApiParam(value = "是否是按参与培训人数降序",required = false) @RequestParam(value="isTrainPeoplesDesc",required = false)String isTrainPeoplesDesc,
                                                                       @ApiParam(value = "地址code",required = false) @RequestParam(value="addressCode",required = false)String addressCode,
                                                                       @ApiParam(value = "第几页",required = true) @RequestParam(value = "index",required = true)int index,
                                                                       @ApiParam(value = "每页大小",required = true) @RequestParam(value = "size",required = true)int size){
         logger.info("trainTitle="+trainTitle+",isTrainDateDesc="+isTrainDateDesc+",isTrainPeoplesDesc="+isTrainDateDesc+",index="+index+",size="+size);
        int count=0;
        PagesUtil pagesUtil=new PagesUtil();
        pagesUtil.setPageSize(size);
        pagesUtil.setCurrentPage(index);
        if(index<1){
            pagesUtil.setCurrentPage(1);
        }

        Paginator<List<TrainInfo>> paginator=null;
        try {
            int total=trainInfoService.queryFrontTrainInfoCount(trainTitle,addressCode);
            logger.info("total="+total);
            pagesUtil.setTotalCount(total);

            List<TrainInfo> trainInfos=null;
            if(StringUtils.isEmpty(isTrainDateDesc)||"0".equals(isTrainDateDesc)){
                isTrainDateDesc=null;
                trainInfos=trainInfoService.queryFrontTraInfoListOrderByTrainDate(trainTitle,addressCode,isTrainDateDesc,(pagesUtil.getCurrentPage()-1)*size,size);
            }
            if(StringUtils.isEmpty(isTrainPeoplesDesc)||"0".equals(isTrainPeoplesDesc)){
                isTrainPeoplesDesc=null;
                trainInfos=trainInfoService.queryFrontTraInfoListOrderByTrainPeoples(trainTitle,addressCode,isTrainPeoplesDesc,(pagesUtil.getCurrentPage()-1)*size,size);
            }


            if(!StringUtils.isEmpty(isTrainPeoplesDesc)&&"1".equals(isTrainPeoplesDesc)){
                trainInfos=trainInfoService.queryFrontTraInfoListOrderByTrainPeoples(trainTitle,addressCode,isTrainPeoplesDesc,(pagesUtil.getCurrentPage()-1)*size,size);
            }
            // 如果两种排序传的值都为1 则时间排序的优先级高
            if(!StringUtils.isEmpty(isTrainDateDesc)&&"1".equals(isTrainDateDesc)){
                trainInfos=trainInfoService.queryFrontTraInfoListOrderByTrainDate(trainTitle,addressCode,isTrainDateDesc,(pagesUtil.getCurrentPage()-1)*size,size);
            }
            logger.info("trainInfos="+trainInfos);
            paginator=new Paginator<List<TrainInfo>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                    pagesUtil.getTotalCount(),trainInfos);
            return new HttpResponseEntity<Paginator<List<TrainInfo>>>(paginator,HttpStatus.OK);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("query trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @ApiOperation(value = "查询培训统计信息",notes = "查询培训统计信息",response = String.class,tags = {"培训信息(前端)"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/info/total/",method = RequestMethod.GET)
    public HttpResponseEntity<TrainInfoTotalDto> getFrontTrainInfoTotal( @ApiParam(value = "培训时间",required = true) @RequestParam(value="trainDate",required = true)String trainDate) {
         //查询培训统计信息
        //1 查询所有区县
        // 2 查询每个区县对应的培训人数
        TrainInfoTotalDto trainInfoTotalDto=new TrainInfoTotalDto();
        String geoCode = SubStringUtil.separateGeoCode("520600000000","3");
        logger.info("======================================code:" + geoCode);
        List<GeoCodings> geoCodingses = geoCodingsService.getGeoCodingsByCode("520600000000",geoCode);
        if (null!=geoCodingses){
            trainInfoTotalDto.setGeoCodeList(geoCodingses);
        }
        float trainPeoplesTotal=trainInfoService.queryTrainPeoplesTotal(trainDate);
        List<String> trainPeoplePerGeo=new ArrayList<>();
        for(GeoCodings geoCodings:geoCodingses){
          int trainPeople=  trainInfoService.queryTrainPeoplesTotalByGeo(trainDate,geoCodings.getId());
            double trainPeopleRate= 0.0;
            String trainPeopleRateStr=null;
            StringBuilder sb=new StringBuilder();
//            if(trainPeople!=0&&trainPeoplesTotal!=0.0){
//                trainPeopleRate=  (trainPeople*1.0/trainPeoplesTotal)*100;
//            }
//            DecimalFormat df=new DecimalFormat("#.00");
//            if(0.0!=trainPeopleRate){
//                trainPeopleRateStr=  df.format(trainPeopleRate);
//            }
            sb.append(trainPeople);
//            if(!StringUtils.isEmpty(trainPeopleRateStr)){
//                sb.append("("+trainPeopleRateStr+"%)");
//            }
            trainPeoplePerGeo.add(sb.toString());
        }
        trainInfoTotalDto.setTrainPeoples(trainPeoplePerGeo);
        return new HttpResponseEntity<TrainInfoTotalDto>(trainInfoTotalDto,HttpStatus.OK);
    }

}
